<template>
  <div style="text-align: center">
    <div style="width: 100%;height: 86vh; overflow: auto; /* 超出部分隐藏，并出现滚动条 */">
      <div style="width: 100%;margin-bottom: 10px;background: white"
           v-for="(item,index) in questionList" :key="index">
        <span style="color: red;font-size: 15px">问题{{item.count}}:{{ item.question }}</span><br>
        <span style="font-size: 15px">回答:{{ item.answer }}</span>
      </div>
    </div>
    <!--    问题输入-->
    <div style="width: 100%;display: flex; align-items: flex-start;">
      <van-field
          v-model="question"
          rows="2"
          type="textarea"
          placeholder="请输入问题"
      >
        <template #button>
          <van-button @click="toQuestion">搜索</van-button>
        </template>
      </van-field>
    </div>
    <!--    尾部-->
    <BottomPanel/>
  </div>
</template>


<script>
import BottomPanel from "@/views/bottomPanel.vue";

export default {
  components: {BottomPanel},
  data() {
    return {
      question: '',
      streamedAnswer: '',
      answer: '',
      emitter: null,
      //集合
      questionList: [],
      //次数
      count: 0
    }
  },
  created() {
  },
  beforeDestroy() {
    if (this.emitter) {
      this.emitter.close();
    }
  },
  methods: {
    toQuestion() {
      this.answer = '';
      if (this.question === '') {
        this.$toast('请输入问题')
      } else {
        this.count++
        this.questionList.push({count: this.count, question: this.question, answer: ''});
        if (this.emitter) {
          this.emitter.close();
        }
        this.emitter = new EventSource('http://localhost:8081/ai/chat/ask?question=' + this.question);
        // 处理流式数据
        this.emitter.onmessage = (event) => {
          this.answer += event.data;
          const index = this.questionList.length - 1;
          this.questionList[index].answer = this.answer;
        };
        this.emitter.onerror = (error) => {
          console.error('SSE 错误：', error);
        };
      }
      this.question = '';
    }
  }
}
</script>


<style>

</style>